package com.ny.service.impl;

import com.ny.entity.Devices;
import com.ny.mapper.DeviceMapper;
import com.ny.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class DeviceServiceImpl implements DeviceService {
    
    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public List<Devices> findAll() {
        return deviceMapper.selectAllDevice();
    }
    
    @Override
    public List<Devices> findByName(String name) {
        return deviceMapper.findByName(name);
    }
    
    @Override
    public int deleteByDeviceId(int deviceId) {
        return (int) deviceMapper.deleteDeviceById(deviceId);
    }
    
    @Override
    public List<Devices> findByNameLike(String name) {
        // 使用MongoDB的正则表达式查询实现模糊匹配
        // 这里需要在DeviceMapper中添加相应方法
        return deviceMapper.findByNameLike(name);
    }
    
    @Override
    public Devices addDevice(Devices device) {
        return deviceMapper.save(device);
    }
    
    @Override
    public Devices updateDevice(Devices device) {
        return deviceMapper.save(device);
    }
    
    @Override
    public Devices findByDeviceId(int deviceId) {
        List<Devices> devices = deviceMapper.findByDeviceId(deviceId);
        return devices.isEmpty() ? null : devices.get(0);
    }
    
    @Override
    public void updateDeviceNameByDeviceId(Integer deviceId, String name) {
        // 先根据设备ID查找设备
        Optional<Devices> deviceOptional = deviceMapper.findByDeviceId(deviceId);
        // 如果找到了设备，则更新其名称并保存
        if (deviceOptional.isPresent()) {
            Devices device = deviceOptional.get();
            device.setName(name);
            deviceMapper.save(device);
        }
    }
}